public class TruncateSentence {

    public static String getSubString(String s, int k){
        int spNum=k;
        String res="";
        int end=0;
        for (int i = 0; i <s.length() ; i++) {
            if(spNum>0){
                if(' '==s.charAt(i)){
                    --spNum;
                }
            }else {
                end=i-1;
                break;
            }
        }
        if(spNum>0){
            end=s.length();
        }
        return s.substring(0,end);
    }

    public static void main(String[] args) {
        getSubString("Hello how are you Contestant",4);
    }
}
